<% layout('/layouts/default.html', {title: '生产配方管理', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(stFormulaName.isNewRecord ? '新增生产配方' : '编辑生产配方')}
			</div>
			<div class="box-tools pull-right">
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${stFormulaName}" action="${ctx}/st/formula/stFormulaName/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>
				<#form:hidden path="id"/>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('配方编码')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="code" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('使用状态')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="useState" dictType="st_use_status" blankOption="true" class="form-control digits" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required">*</span> ${text('产品 id')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="productId" items="${productList}" itemLabel="productName" blankOption="true" itemValue="id" class="form-control required" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('审批状态')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="approveState" dictType="st_approve_state" blankOption="true" class="form-control digits" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('审批人编码')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="approveManCode" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('审批人')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="approveManName" maxlength="5" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required hide">*</span> ${text('备注信息')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10">
								<#form:textarea path="remarks" rows="4" maxlength="500" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<h4 class="form-unit">${text('生产配方明细')}</h4>
				<div class="ml10 mr10">
					<table id="stFormulaDetailDataGrid"></table>
					<% if (hasPermi('st:formula:stFormulaName:edit')){ %>
						<a href="#" id="stFormulaDetailDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10"><i class="fa fa-plus"></i> ${text('增行')}</a>
					<% } %>
				</div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('st:formula:stFormulaName:edit')){ %>
							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<!--<script src="https://cdn.bootcdn.net/ajax/libs/mathjs/8.1.0/math.js"></script>-->
<script src="https://cdn.bootcdn.net/ajax/libs/bignumber.js/9.0.1/bignumber.js"></script>
<script>
//初始化生产配方明细DataGrid对象
$("#stFormulaDetailDataGrid").dataGrid({

	data: ${toJson(stFormulaName.stFormulaDetailList)},
	datatype: "local", // 设置本地数据
	autoGridHeight: function(){return 'auto'}, // 设置自动高度
	
	// 设置数据表格列
	columnModel: [
		{header:'状态', name:'status', editable:true, hidden:true},
		{header:'主键', name:'id', editable:true, hidden:true},
		{header:'${text("原料名称")}', name:'materialName', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control',
				items: $.merge([{materialName:'&nbsp;',id:''}], ${materialList}),
				itemLabel: 'materialName', itemValue: 'id', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
				}
			}
		},
		{header:'${text("占比%")}', name:'percentIn', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number',dataInit:function (element) {
					$(element).attr("data-calc","calc");
					$(element).bind("input propertychange", function() {
						var $e = $(element);
						var val = $e.val();
						if(""== val) return;
						var n1=new BigNumber(val);
						var n2=new BigNumber(10);
						var res = n1.times(n2).toNumber();
						var formula = $e.closest('td').next();
						formula.find('.form-control').val(res);
						$('#stFormulaDetailDataGrid').dataGrid("footerData", "set", {
							'materialName' : '<em>合计：&nbsp;</em>',
							'percentIn': '<em>'+calc()+'% &nbsp;</em>',
							'perWeigh': '待定'
						}, false);
					});
				}
			}
		},
		{header:'${text("每吨重量")}', name:'perWeigh', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number',"readonly":true}},
		{header:'${text("配方id")}', name:'formulaNameId.id', editable:true, hidden:true},
		{header:'${text("操作")}', name:'actions', width:80, sortable:false, fixed:true, formatter: function(val, obj, row, act){
			var actions = [];
			if (val == 'new'){
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#stFormulaDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}else{
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#stFormulaDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}
			return actions.join('');
		}, editoptions: {defaultValue: 'new'}}
	],
	
	// 编辑表格参数
	editGrid: true,				// 是否是编辑表格
	editGridInitRowNum: 1,		// 编辑表格的初始化新增行数
	editGridAddRowBtn: $('#stFormulaDetailDataGridAddRowBtn'),	// 子表增行按钮
	editGridAddRowInitData: {id: '', status: Global.STATUS_NORMAL},	// 新增行的时候初始化的数据
	
	// 编辑表格的提交数据参数
	editGridInputFormListName: 'stFormulaDetailList', // 提交的数据列表名
	editGridInputFormListAttrs: 'status,id,materialName,percentIn,perWeigh,formulaNameId.id,', // 提交数据列表的属性字段
	showFooter: true,
	// 加载成功后执行事件
	ajaxSuccess: function(data){
		
	}
});
</script>
<script>
	function calc() {
		var $calc = $("input[data-calc]");
		var total=0;
		$.each($calc,function (i, item) {
			var val = $(item).val();
			total=add(total,val);
		});
		return total;
	}
	function add() {
		// 需要相加的数字
		let _args = arguments;
		// 获取到所有小数点的位数
		let _pointArray = Array.prototype.map.call(_args, (item) => {
			let _itemArray = item.toString().split(".")
			return _itemArray.length > 1 ? _itemArray[1].length:0
		})
		// 最大小数点位数
		let _maxPoint = Math.max.apply(null, _pointArray);
		// 放大的比值
		let _scale = Math.pow(10,_maxPoint)
		// 最终的返回值
		return Array.prototype.reduce.apply(_args, [(a,b) =>  a + (b * _scale), 0]) / _scale

	}
	$("#inputForm").validate({
	submitHandler: function(form){
		// var arr=["1.25", "8.75", "5", "0.3", "0.15", "0.06", "0.1", "4.82", "5", "0.2", "0.5", "5", "28.07", "40.8"]
		// var total=0;
		// $.each(arr,function (i,item) {
		// 	total=add(total,item);
		// 	console.info(item,total);
		// });
		// return;


		if(calc() !=100){
			js.showMessage("请确保合计是 100%");
			return;
		}
		js.ajaxSubmitForm($(form), function(data){
			js.showMessage(data.message);
			if(data.result == Global.TRUE){
				js.closeCurrentTabPage(function(contentWindow){
					contentWindow.page();
				});
			}
		}, "json");
    }
});
</script>